package com.itfreer.gather.main;

import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.RelativeLayout;

import com.esri.arcgisruntime.concurrent.ListenableFuture;
import com.esri.arcgisruntime.data.Feature;
import com.esri.arcgisruntime.data.FeatureQueryResult;
import com.esri.arcgisruntime.geometry.SpatialReference;
import com.esri.arcgisruntime.layers.FeatureLayer;
import com.esri.arcgisruntime.mapping.ArcGISMap;
import com.esri.arcgisruntime.mapping.view.BackgroundGrid;
import com.esri.arcgisruntime.mapping.view.MapView;
import com.itfreer.arcgis.draw.DrawPolyLineTool;
import com.itfreer.arcgis.draw.DrawPolygonTool;
import com.itfreer.arcgis.draw.DrawTool;
import com.itfreer.arcgis.draw.DrawToolManager;
import com.itfreer.arcgis.edit.CreateNewFeatureCommand;
import com.itfreer.arcgis.edit.CreatePolygonTool;
import com.itfreer.arcgis.edit.CreateSplitPolylineTool;
import com.itfreer.arcgis.edit.DeleteSelectFeatureCommand;
import com.itfreer.arcgis.edit.EditToolUtils;
import com.itfreer.arcgis.edit.GPSLineDrawCommand;
import com.itfreer.arcgis.edit.GPSPointDrawCommand;
import com.itfreer.arcgis.edit.ScreenCenterDrawCommand;
import com.itfreer.arcgis.edit.SplitSelectFeatureCommand;
import com.itfreer.arcgis.edit.UnionSelectFeatureCommand;
import com.itfreer.arcgis.gps.GPSAccuracyListener;
import com.itfreer.arcgis.gps.GPSStopListener;
import com.itfreer.arcgis.gps.GpsOption;
import com.itfreer.arcgis.layer.LayerLoader;
import com.itfreer.arcgis.layer.LayerSelect;
import com.itfreer.arcgis.utils.MapUtils;
import com.itfreer.arcgis.utils.MapViewUtils;
import com.itfreer.gather.R;
import com.itfreer.gather.main.arcgis.SelectTouchListener;
import com.itfreer.gather.main.fragment.AnalyseFragment;
import com.itfreer.gather.main.fragment.MapLayerFragment;
import com.itfreer.gather.main.fragment.MeasureFragment;
import com.itfreer.gather.message.MessageActivity;
import com.itfreer.gather.setting.SettingActivity;
import com.itfreer.gather.task.TaskActivity;
import com.itfreer.ui.activity.BaseActivity;
import com.itfreer.ui.base.DialogCloseListener;
import com.itfreer.ui.base.DialogResult;
import com.itfreer.ui.base.TextView;
import com.itfreer.ui.base.domain.DomainRadioDialog;
import com.itfreer.utils.collection.SerializableMap;
import com.itfreer.utils.common.AlertUtils;
import com.itfreer.utils.common.RequestPermissionsUtils;
import com.itfreer.utils.common.ToastUtils;
import com.itfreer.utils.config.ConfigManager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;

/**
 * 主界面，全屏展示
 */
public class MainActivity extends BaseActivity {

    private MapView mMapView;

    private Fragment searchFragment;
    private Fragment mapLayerFragment;
    private Fragment analyseFragment;
    private MeasureFragment measureFragment;

    // 选择要素
    private Feature selectFeature;

    // 要素选择
    private TextView main_select_icon;
    private TextView main_select_text;

    // 定位
    private TextView main_local_icon;
    private TextView main_local_text;

    // 拉框选择
    SelectTouchListener touchListener;

    // gps线
    private TextView main_edit_gps_line;
    private TextView main_edit_gps_line2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 无title
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        // 全屏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        // 防止休眠
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        setContentView(R.layout.main_activity);
        ConfigManager.setContext(this);
        // 要素选择
        main_select_icon = (TextView) findViewById(R.id.main_select_icon);
        main_select_text = (TextView) findViewById(R.id.main_select_text);
        // 定位
        main_local_icon = (TextView) findViewById(R.id.main_local_icon);
        main_local_text = (TextView) findViewById(R.id.main_local_text);

        // gps线
        main_edit_gps_line = (TextView) findViewById(R.id.main_edit_gps_line);
        main_edit_gps_line2 = (TextView) findViewById(R.id.main_edit_gps_line2);

        // 地图对象
        mMapView = findViewById(R.id.mapView);
        ArcGISMap map = new ArcGISMap(SpatialReference.create((int)ConfigManager.getConfig("MapSpatialReference")));
        mMapView.setMap(map);

        // 去掉网格
        BackgroundGrid backgroundGrid = new BackgroundGrid();
        backgroundGrid.setColor(0xf6f6f6f6);
        backgroundGrid.setGridLineWidth(0);
        mMapView.setBackgroundGrid(backgroundGrid);
        mMapView.setAttributionTextVisible(false);

        // 采编
        final RelativeLayout patrolContrl = (RelativeLayout) findViewById(R.id.patrolContrl);
        final TextView patrolContrlText = (TextView) findViewById(R.id.patrolContrlText);
        final RelativeLayout main_edit_tool = (RelativeLayout) findViewById(R.id.main_edit_tool);
        patrolContrl.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if (patrolContrlText.getText().equals("采编")) {
                    final List<FeatureLayer> editFeatuerLayers = EditToolUtils.getEditLayer(mMapView);
                    if (editFeatuerLayers == null || editFeatuerLayers.size() == 0) {
                        ToastUtils.showShort(ConfigManager.getContext(), "没有可编辑的图层");
                        return;
                    }
                    EditToolUtils.showSelectEditLayer(editFeatuerLayers, new DialogCloseListener() {
                        @Override
                        public void OnClosed(Object send, DialogResult result) {
                            if (result == DialogResult.Ok) {
                                DomainRadioDialog dialog = (DomainRadioDialog) send;
                                Object tempObjectId = dialog.getCheckedValue();
                                if (tempObjectId != null) {
                                    String id = tempObjectId.toString();
                                    FeatureLayer featureLayer = EditToolUtils.getEditSelectFeatureLayerById(mMapView,
                                            id);
                                    if (featureLayer != null) {
                                        ConfigManager.setConfig(EditToolUtils.eidtFeatureLayerKey, featureLayer);
                                        main_edit_tool.setVisibility(View.VISIBLE);
                                        patrolContrl.setBackgroundResource(R.drawable.navigation_circle_end);

                                        // 显示中心点图标
                                        findViewById(R.id.centerLocation).setVisibility(View.VISIBLE);

                                        patrolContrlText.setText("结束");
                                    }
                                }
                            }
                        }
                    });
                } else {
                    // 如果当前编辑工具不为空，并且有绘制元素则弹出提示框提示
                    if (DrawToolManager.GetCurrentTool() != null && DrawToolManager.GetCurrentTool().hasDraw()) {
                        AlertUtils.dialog(MainActivity.this, "系统提示", "当前编辑进行中，是否确认结束？",
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        endEditOperator(main_edit_tool, patrolContrl, patrolContrlText);
                                    }
                                }, new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {

                                    }
                                });
                    } else {
                        endEditOperator(main_edit_tool, patrolContrl, patrolContrlText);
                    }
                }
            }
        });

        // GPS停止
        GpsOption.instance.setGpsStopListener(new GPSStopListener() {
            @Override
            public void stop() {
                main_local_text.setText("定位");
                main_local_icon.setTextColor(Color.parseColor("#303059"));
                main_local_icon.setTextSize(20);

                main_edit_gps_line.setText("GPS线");
                main_edit_gps_line2.setText("GPS线");
            }
        });

        GpsOption.instance.setGpsAccuracyListener(new GPSAccuracyListener() {
            @Override
            public void accuracyUpdate(double accuracy) {
                if(accuracy<=8){
                    main_local_text.setText("高");
                }else if(accuracy<=15){
                    main_local_text.setText("中");
                }else{
                    main_local_text.setText("低");
                }
            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
        // 加载图层
        LayerLoader.instance.loadLayer(mMapView);
    }

    /**
     * 图层管理
     * @param v
     */
    public void onLayerManageClick(View v) {
        if (mapLayerFragment == null) {
            mapLayerFragment = new MapLayerFragment(mMapView);
        }

        FragmentTransaction ft2 = getFragmentManager().beginTransaction();
        ft2.replace(R.id.fragment, mapLayerFragment);
        ft2.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
        ft2.addToBackStack(null);
        ft2.commit();
    }

    /**
     * 分析管理
     * @param v
     */
    public void onAnalyseClick(View v) {
        int selectSize = LayerSelect.instance.getSelectedFeatures().size();
        if (selectSize <= 0) {
            ToastUtils.showLong(ConfigManager.getContext(), "请先选取要素！");
            return;
        } else if (selectSize > 1) {
            ToastUtils.showLong(ConfigManager.getContext(), "请只选取一个要素！");
            return;
        }

        // 获取选择图层
        if (LayerSelect.instance.getSelectedFeatureLayer().getName().equals("JC_SLZY")) {
            if (analyseFragment == null) {
                analyseFragment = new AnalyseFragment(mMapView);
            }

            FragmentTransaction ft2 = getFragmentManager().beginTransaction();
            ft2.replace(R.id.fragment, analyseFragment);
            ft2.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
            ft2.addToBackStack(null);
            ft2.commit();
        } else {
            ToastUtils.showLong(ConfigManager.getContext(), "请选择资源监测数据图层要素！");
        }
    }

    /**
     * 手绘
     *
     * @param v
     */
    public void doClickDrawByUser(View v) {
        EditToolUtils.updateDrawTool(mMapView);
    }

    /**
     * 中心点落点(编辑)
     *
     * @param v
     */
    public void doClickShowCenterLocation(View v) {
        // 去除之前工具状态
        changeCurrentCreateToolStatus(1);
        ScreenCenterDrawCommand screenCreateCommand = new ScreenCenterDrawCommand(CreatePolygonTool.class);
        Map<String, Object> params = new HashMap<>();
        params.put("mapView", mMapView);
        params.put("activity", this);
        screenCreateCommand.Execute(params);
    }

    /**
     * GPS落点(编辑)
     *
     * @param v
     */
    public void doClickShowGPSPointLocation(View v) {
        // 去除之前工具状态
        changeCurrentCreateToolStatus(2);
        GPSPointDrawCommand gpsPointDrawCommand = new GPSPointDrawCommand(CreatePolygonTool.class);
        Map<String, Object> params = new HashMap<>();
        params.put("mapview", this.mMapView);
        gpsPointDrawCommand.Execute(params);
    }

    GPSLineDrawCommand gpsEditLineDrawCommand;

    /**
     * GPS落线(编辑)
     *
     * @param v
     */
    public void doClickShowGPSLineLocation(View v) {
        if(main_edit_gps_line.getText().equals("GPS线")){
            main_edit_gps_line.setText("停止");

            // 去除之前工具状态
            changeCurrentCreateToolStatus(2);
            gpsEditLineDrawCommand = new GPSLineDrawCommand(CreatePolygonTool.class);
            Map<String, Object> params = new HashMap<>();
            params.put("mapview", this.mMapView);
            gpsEditLineDrawCommand.Execute(params);
        }else{
            main_edit_gps_line.setText("GPS线");
            // 去除之前工具状态
            changeCurrentCreateToolStatus(2);
        }
    }

    /**
     * 回退
     *
     * @param v
     */
    public void doClickDrawBack(View v) {
        if (DrawToolManager.GetCurrentTool() == null || !DrawToolManager.GetCurrentTool().hasDraw()) {
            ToastUtils.showShort(MainActivity.this, "请先开始绘画操作！");
            return;
        }
        DrawToolManager.GetCurrentTool().Back();
    }

    /**
     * 放弃
     *
     * @param v
     */
    public void doClickDrawDrop(View v) {
        if (DrawToolManager.GetCurrentTool() == null || !DrawToolManager.GetCurrentTool().hasDraw()) {
            ToastUtils.showShort(MainActivity.this, "当前无编辑操作！");
            return;
        }
        DrawToolManager.GetCurrentTool().Clear();

        clearCurrentToolStatus();
    }

    /**
     * 创建
     *
     * @param v
     */
    public void doClickDrawFinish(View v) {
        if (DrawToolManager.GetCurrentTool() == null || DrawToolManager.GetCurrentTool().GetGeometry() == null
                || DrawToolManager.GetCurrentTool().GetGeometry().isEmpty()) {
            ToastUtils.showShort(MainActivity.this, "当前无编辑操作！");
            return;
        }
        CreateNewFeatureCommand command = new CreateNewFeatureCommand();
        command.Execute(null);
        DrawToolManager.GetCurrentTool().Clear();

        clearCurrentToolStatus();
    }

    /**
     * 删除
     *
     * @param v
     */
    public void doClickDrawDelete(View v) {
        DeleteSelectFeatureCommand command = new DeleteSelectFeatureCommand();
        command.Execute(null);
    }

    /**
     * 分割选项操作
     *
     * @param v
     */
    public void doClickSplitDrawOption(View v) {
        final List<FeatureLayer> editFeatuerLayers = EditToolUtils.getEditLayer(mMapView);
        if (editFeatuerLayers == null || editFeatuerLayers.size() == 0) {
            ToastUtils.showShort(ConfigManager.getContext(), "没有可编辑的图层");
            return;
        }
        setOperatorToolStatus(2);
    }

    /**
     * 分割绘画
     *
     * @param v
     */
    public void doClickSplitDraw(View v) {
        FeatureLayer featureLayer = EditToolUtils.getCurrentEditFeatureLayer();
        if (featureLayer == null)
            return;

        final ListenableFuture<FeatureQueryResult> selects = featureLayer.getSelectedFeaturesAsync();
        if (selects == null)
            return;

        selects.addDoneListener(new Runnable() {
            @Override
            public void run() {
                try {
                    FeatureQueryResult result = selects.get();
                    Iterator<Feature> iterator = result.iterator();
                    List<Feature> features = new ArrayList<>();
                    while (iterator.hasNext()) {
                        features.add(iterator.next());
                    }
                    if (features.size() == 0) {
                        ToastUtils.showShort(MainActivity.this, "请选择要分割的要素");
                        return;
                    } else if (features.size() > 1) {
                        ToastUtils.showShort(MainActivity.this, "请选择一个要素进行分割");
                        return;
                    } else {
                        CreateSplitPolylineTool tool = new CreateSplitPolylineTool();
                        tool.Draw(mMapView, null);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 中心点落点(分割)
     *
     * @param v
     */
    public void doClickSplitShowCenterLocation(View v) {
        FeatureLayer featureLayer = EditToolUtils.getCurrentEditFeatureLayer();
        if (featureLayer == null)
            return;

        final ListenableFuture<FeatureQueryResult> selects = featureLayer.getSelectedFeaturesAsync();
        if (selects == null)
            return;

        selects.addDoneListener(new Runnable() {
            @Override
            public void run() {
                try {
                    FeatureQueryResult result = selects.get();
                    Iterator<Feature> iterator = result.iterator();
                    List<Feature> features = new ArrayList<>();
                    while (iterator.hasNext()) {
                        features.add(iterator.next());
                    }
                    if (features.size() == 0) {
                        ToastUtils.showShort(MainActivity.this, "请选择要分割的要素");
                        return;
                    } else if (features.size() > 1) {
                        ToastUtils.showShort(MainActivity.this, "请选择一个要素进行分割");
                        return;
                    } else {
                        ScreenCenterDrawCommand screenCreateCommand = new ScreenCenterDrawCommand(
                                CreateSplitPolylineTool.class);
                        Map<String, Object> params = new HashMap<>();
                        params.put("mapView", mMapView);
                        params.put("activity", MainActivity.this);
                        screenCreateCommand.Execute(params);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * GPS落点(分割)
     *
     * @param v
     */
    public void doClickSplitShowGPSPointLocation(View v) {
        FeatureLayer featureLayer = EditToolUtils.getCurrentEditFeatureLayer();
        if (featureLayer == null)
            return;

        final ListenableFuture<FeatureQueryResult> selects = featureLayer.getSelectedFeaturesAsync();
        if (selects == null)
            return;

        selects.addDoneListener(new Runnable() {
            @Override
            public void run() {
                try {
                    FeatureQueryResult result = selects.get();
                    Iterator<Feature> iterator = result.iterator();
                    List<Feature> features = new ArrayList<>();
                    while (iterator.hasNext()) {
                        features.add(iterator.next());
                    }
                    if (features.size() == 0) {
                        ToastUtils.showShort(MainActivity.this, "请选择要分割的要素");
                        return;
                    } else if (features.size() > 1) {
                        ToastUtils.showShort(MainActivity.this, "请选择一个要素进行分割");
                        return;
                    } else {
                        GPSPointDrawCommand gpsPointDrawCommand = new GPSPointDrawCommand(
                                CreateSplitPolylineTool.class);
                        Map<String, Object> params = new HashMap<>();
                        params.put("mapview", MainActivity.this.mMapView);
                        gpsPointDrawCommand.Execute(params);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    GPSLineDrawCommand gpsSplitDrawCommand = null;

    /**
     * GPS线(分割)
     *
     * @param v
     */
    public void doClickSplitShowGPSLineLocation(View v) {
        FeatureLayer featureLayer = EditToolUtils.getCurrentEditFeatureLayer();
        if (featureLayer == null)
            return;

        final ListenableFuture<FeatureQueryResult> selects = featureLayer.getSelectedFeaturesAsync();
        if (selects == null)
            return;

        selects.addDoneListener(new Runnable() {
            @Override
            public void run() {
                try {
                    FeatureQueryResult result = selects.get();
                    Iterator<Feature> iterator = result.iterator();
                    List<Feature> features = new ArrayList<>();
                    while (iterator.hasNext()) {
                        features.add(iterator.next());
                    }
                    if (features.size() == 0) {
                        ToastUtils.showShort(MainActivity.this, "请选择要分割的要素");
                        return;
                    } else if (features.size() > 1) {
                        ToastUtils.showShort(MainActivity.this, "请选择一个要素进行分割");
                        return;
                    } else {
                        if(main_edit_gps_line2.getText().equals("GPS线")){
                            main_edit_gps_line2.setText("停止");
                            changeCurrentCreateToolStatus(-1);
                            gpsSplitDrawCommand = new GPSLineDrawCommand(CreateSplitPolylineTool.class);
                            Map<String, Object> params = new HashMap<>();
                            params.put("mapview", MainActivity.this.mMapView);
                            gpsSplitDrawCommand.Execute(params);
                        }else{
                            main_edit_gps_line2.setText("GPS线");
                            changeCurrentCreateToolStatus(-1);
                        }
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 分割回退操作
     *
     * @param v
     */
    public void doClickSplitDrawBack(View v) {
        if (DrawToolManager.GetCurrentTool() == null
                || !(DrawToolManager.GetCurrentTool() instanceof CreateSplitPolylineTool)
                || !DrawToolManager.GetCurrentTool().hasDraw()) {
            ToastUtils.showShort(MainActivity.this, "请先开始分割绘画操作！");
            return;
        }
        DrawToolManager.GetCurrentTool().Back();
    }

    /**
     * 分割放弃操作
     *
     * @param v
     */
    public void doClickSplitDrawDrop(View v) {
        if (DrawToolManager.GetCurrentTool() == null
                || !(DrawToolManager.GetCurrentTool() instanceof CreateSplitPolylineTool)
                || !DrawToolManager.GetCurrentTool().hasDraw()) {
            ToastUtils.showShort(MainActivity.this, "请先开始分割绘画操作！");
            return;
        }
        DrawToolManager.GetCurrentTool().Clear();
    }

    /**
     * 执行分割操作
     *
     * @param v
     */
    public void doClickkSplit(View v) {
        if (DrawToolManager.GetCurrentTool() == null
                || !(DrawToolManager.GetCurrentTool() instanceof CreateSplitPolylineTool)
                || DrawToolManager.GetCurrentTool().GetGeometry() == null
                || DrawToolManager.GetCurrentTool().GetGeometry().isEmpty()) {
            ToastUtils.showShort(MainActivity.this, "请先开始分割绘画操作！");
            return;
        }
        SplitSelectFeatureCommand command = new SplitSelectFeatureCommand();
        command.Execute(null);
    }

    /**
     * 合并操作
     *
     * @param v
     */
    public void doClickMargeDrawOption(View v) {
        final List<FeatureLayer> editFeatuerLayers = EditToolUtils.getEditLayer(mMapView);
        if (editFeatuerLayers == null || editFeatuerLayers.size() == 0) {
            ToastUtils.showShort(ConfigManager.getContext(), "没有可编辑的图层");
            return;
        }
        setOperatorToolStatus(1);
    }

    /**
     * 多选
     *
     * @param v
     */
    public void doClickSelectByRantge(View v) {
        TextView main_mult_select_icon = (TextView) findViewById(R.id.main_mult_select_icon);
        TextView main_mult_select_text = (TextView) findViewById(R.id.main_mult_select_text);
        if (main_mult_select_text.getText().equals("选择")) {
            LayerSelect.instance.select(this, mMapView);
            main_mult_select_text.setText("取消选择");
            main_mult_select_icon.setTextColor(Color.parseColor("#47b34d"));
            main_mult_select_icon.setTextSize(23);

            List<FeatureLayer> featureLayers = new ArrayList<>();
            FeatureLayer featureLayer = EditToolUtils.getCurrentEditFeatureLayer();
            featureLayers.add(featureLayer);

            // 拉框完毕更新选择按钮状态
            touchListener = new SelectTouchListener(this, mMapView, featureLayers,
                    new SelectTouchListener.CustomSelectTouch() {
                        @Override
                        public void onTouch(View view, MotionEvent event) {
                            switch (event.getAction()) {
                                case MotionEvent.ACTION_UP:
                                    updateMultSelectButtonDefault();
                                    break;
                                default:
                                    break;
                            }
                        }
                    });
            mMapView.setOnTouchListener(touchListener);
        } else {
            if (EditToolUtils.getCurrentEditFeatureLayer() != null)
                EditToolUtils.getCurrentEditFeatureLayer().clearSelection();
            updateMultSelectButtonDefault();
        }
    }

    /**
     * 取消多选状态
     */
    private void updateMultSelectButtonDefault() {
        TextView main_mult_select_icon = (TextView) findViewById(R.id.main_mult_select_icon);
        TextView main_mult_select_text = (TextView) findViewById(R.id.main_mult_select_text);
        main_mult_select_text.setText("选择");
        main_mult_select_icon.setTextColor(Color.parseColor("#FFFFFF"));
        main_mult_select_icon.setTextSize(20);
        if (touchListener != null) {
            touchListener.setActive(false);
            touchListener = null;
        }
    }

    /**
     * 清除当前工具状态
     */
    private void clearCurrentToolStatus() {
        // 如果开启了屏幕定位、GPS定位功能，清除屏幕定位功能
        changeCurrentCreateToolStatus(-1);

        // 如果当前工具不为空，清空当前工具的绘画状态，并且置空当前工具
        DrawTool drawTool = DrawToolManager.GetCurrentTool();
        if (drawTool != null) {
            drawTool.Clear();
            DrawToolManager.setCurrentTool(null);
        }
    }

    /**
     * 更改当前编辑按钮状态
     */
    private void changeCurrentCreateToolStatus(Integer type) {
        if (gpsEditLineDrawCommand != null) {
            gpsEditLineDrawCommand.destory();
            gpsEditLineDrawCommand = null;
        }

        if (gpsSplitDrawCommand != null) {
            gpsSplitDrawCommand.destory();
            gpsSplitDrawCommand = null;
        }
    }

    /**
     * 执行合并操作
     *
     * @param v
     */
    public void doClickMarge(View v) {
        UnionSelectFeatureCommand command = new UnionSelectFeatureCommand();
        command.Execute(null);
    }

    /**
     * 结束编辑操作
     */
    private void endEditOperator(View main_edit_tool, View patrolContrl, TextView patrolContrlText) {
        ConfigManager.setConfig(EditToolUtils.eidtFeatureLayerKey, null);
        DrawToolManager.setCurrentTool(null);
        main_edit_tool.setVisibility(View.GONE);
        setOperatorToolStatus(-1);
        patrolContrl.setBackgroundResource(R.drawable.navigation_circle);
        patrolContrlText.setText("采编");

        // 取消屏幕中心点显示
        findViewById(R.id.centerLocation).setVisibility(View.GONE);
    }

    /**
     * 询问是否允许访问本地文件权限回调
     */
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        if (requestCode == RequestPermissionsUtils.OPEN_GPS) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                GpsOption.instance.openGPS(mMapView);
            } else {
                GpsOption.instance.stopGPS();
                ToastUtils.showLong(MainActivity.this, "您取消了开启定位功能！");
            }
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if (closeFragment()) {
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 关闭Fragment
     *
     * @return
     */
    private boolean closeFragment() {
        if (searchFragment != null && searchFragment.isVisible()) {
            getFragmentManager().popBackStack();
            return true;
        }
        if (mapLayerFragment != null && mapLayerFragment.isVisible()) {
            getFragmentManager().popBackStack();
            return true;
        }
        if (analyseFragment != null && analyseFragment.isVisible()) {
            getFragmentManager().popBackStack();
            return true;
        }
        return false;
    }

    /**
     * 全图
     */
    public void fullMap(View v) {
        MapUtils.fullMap(mMapView);
    }

    /**
     * 改变编辑工具
     */
    public void changeEditTool(View v) {
        setOperatorToolStatus(0);
    }

    /**
     * 设置工具条显示逻辑及状态
     *
     * @param type
     *            工具条类型
     */
    private void setOperatorToolStatus(Integer type) {
        View currentView = null;
        if (type == 0) {
            findViewById(R.id.main_edit_merge).setVisibility(View.GONE);
            findViewById(R.id.main_edit_split).setVisibility(View.GONE);
            currentView = findViewById(R.id.main_edit_option);
        } else if (type == 1) {
            findViewById(R.id.main_edit_option).setVisibility(View.GONE);
            findViewById(R.id.main_edit_split).setVisibility(View.GONE);
            currentView = findViewById(R.id.main_edit_merge);
        } else if (type == 2) {
            findViewById(R.id.main_edit_option).setVisibility(View.GONE);
            findViewById(R.id.main_edit_merge).setVisibility(View.GONE);
            currentView = findViewById(R.id.main_edit_split);
        } else {
            findViewById(R.id.main_edit_option).setVisibility(View.GONE);
            findViewById(R.id.main_edit_split).setVisibility(View.GONE);
            findViewById(R.id.main_edit_merge).setVisibility(View.GONE);
        }

        if (currentView != null) {
            if (currentView.getVisibility() == View.VISIBLE) {
                currentView.setVisibility(View.GONE);
            } else {
                currentView.setVisibility(View.VISIBLE);
            }
        }
        // 更新编辑选择状态为默认状态
        updateMultSelectButtonDefault();

        // 清除当前工具状态
        clearCurrentToolStatus();
    }

    /**
     * 到我的界面
     */
    public void goMyPage(View v) {
        // 新建一个Intent对象
        Intent intent = new Intent();
        // 将map数据添加到封装的myMap中
        final SerializableMap dataMap = new SerializableMap();
        dataMap.setMap(null);
        Bundle bundle = new Bundle();
        bundle.putSerializable("map", dataMap);
        intent.putExtras(bundle);
        // 指定intent要启动的类
        intent.setClass(MainActivity.this, SettingActivity.class);
        // 启动一个新的Activity
        startActivityForResult(intent, 10);
    }

    /**
     * 测量返回值
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 10 && resultCode == 10) {
            // 线测量
            DrawPolyLineTool drawTool = new DrawPolyLineTool();
            drawTool.Draw(mMapView, null);

            if (measureFragment != null && measureFragment.isVisible()) {
                return;
            }
            if (measureFragment == null) {
                measureFragment = new MeasureFragment();
            }
            measureFragment.start(this.mMapView);
            FragmentTransaction ft2 = getFragmentManager().beginTransaction();
            ft2.replace(R.id.fragment, measureFragment);
            ft2.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
            ft2.addToBackStack(null);
            ft2.commit();
        } else if (requestCode == 10 && resultCode == 20) {
            // 面测量
            DrawPolygonTool drawTool = new DrawPolygonTool();
            drawTool.Draw(mMapView, null);

            if (measureFragment != null && measureFragment.isVisible()) {
                return;
            }
            if (measureFragment == null) {
                measureFragment = new MeasureFragment();
            }
            measureFragment.start(this.mMapView);
            FragmentTransaction ft2 = getFragmentManager().beginTransaction();
            ft2.replace(R.id.fragment, measureFragment);
            ft2.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
            ft2.addToBackStack(null);
            ft2.commit();
        }
    }

    /**
     * 到信息界面
     */
    public void goMessagePage(View v) {
        // 新建一个Intent对象
        Intent intent = new Intent();
        // 指定intent要启动的类
        intent.setClass(MainActivity.this, MessageActivity.class);
        // 启动一个新的Activity
        startActivity(intent);
    }

    /**
     * 到任务界面
     */
    public void goTaskPage(View v) {
        // 新建一个Intent对象
        Intent intent = new Intent();
        // 指定intent要启动的类
        intent.setClass(MainActivity.this, TaskActivity.class);
        // 启动一个新的Activity
        startActivity(intent);
    }

    /**
     * 放大
     *
     * @param v
     */
    public void doClickZoomIn(View v) {
        MapViewUtils.DefaultZoomIn(mMapView);
    }

    /**
     * 缩小
     *
     * @param v
     */
    public void doClickZoomOut(View v) {
        MapViewUtils.DefaultZoomOut(mMapView);
    }

    /**
     * 地图定位
     *
     * @param v
     */
    public void doClickLocation(View v) {
        if (main_local_text.getText().equals("定位")) {
            GpsOption.instance.openGPS(mMapView);

            main_local_text.setText("取消定位");
            main_local_icon.setTextColor(Color.parseColor("#47b34d"));
            main_local_icon.setTextSize(23);
        } else {
            GpsOption.instance.stopGPS();

            main_local_text.setText("定位");
            main_local_icon.setTextColor(Color.parseColor("#303059"));
            main_local_icon.setTextSize(20);
        }
    }

    /**
     * 点选要素
     *
     * @param v
     */
    public void doClickSelect(View v) {
        if (main_select_text.getText().equals("选择")) {
            LayerSelect.instance.select(this, mMapView);
            main_select_text.setText("取消选择");
            main_select_icon.setTextColor(Color.parseColor("#47b34d"));
            main_select_icon.setTextSize(23);
        } else {
            LayerSelect.instance.unSelect(this, mMapView);
            main_select_text.setText("选择");
            main_select_icon.setTextColor(Color.parseColor("#303059"));
            main_select_icon.setTextSize(20);
        }
    }

    /**
     * 查看选择要素的详情
     *
     * @param v
     */
    public void doClickInfo(View v) {
        if (LayerSelect.instance.getSelectedFeatures().size() <= 0) {
            ToastUtils.showLong(this, "请先选取要素！");
            return;
        }
        // 新建一个Intent对象
        Intent intent = new Intent();
        // 将map数据添加到封装的myMap中
        final SerializableMap dataMap = new SerializableMap();
        dataMap.setMap(null);
        Bundle bundle = new Bundle();
        bundle.putSerializable("map", dataMap);
        intent.putExtras(bundle);
        // 指定intent要启动的类
        if (LayerSelect.instance.getSelectedFeatureLayer().getName().equals("JC_SLZY")) {
            intent.setClass(MainActivity.this, AttributeEditActivity.class);
        } else {
            intent.setClass(MainActivity.this, AttributeSeeActivity.class);
        }
        // 启动一个新的Activity
        startActivity(intent);
    }

    @Override
    protected void onPause() {
        mMapView.pause();
        super.onPause();
    }

    @Override
    protected void onStop() {
        mMapView.resume();
        super.onStop();
    }

    @Override
    protected void onResume() {
        mMapView.resume();
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        MapUtils.ClearMapLayer(mMapView);
        mMapView.dispose();
        GpsOption.instance.stopGPS();

        super.onDestroy();
    }

    /**
     * 返回时，是否可以退出
     *
     * @return
     */
    protected boolean canExit() {
        return true;
    }
}